import { legacy_createStore , applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import { STORESUMTYPE ,ALLSTORETYPE ,SETLIST,PAYLOADTYPE,TABINDEX,SHOPITEM} from '../Type/Store.d';

const initialState = {
    list:[],
    childrenList:[],
    shopList:[],
}

const routes = (state:STORESUMTYPE = initialState, { type, payload }:ALLSTORETYPE) => {

    switch (type) {

    case SETLIST:
        state.list = payload;
        
        state.childrenList = payload[0].children as PAYLOADTYPE[];
        return {...state}

    case TABINDEX:
        state.childrenList = state.list[payload].children as PAYLOADTYPE[];
        return {...state}

    case SHOPITEM:
        let flag = state.shopList.some(item=>item.id == payload.id);
        if(flag){
            state.shopList.forEach((item,index)=>{
                if(item.id == payload.id){
                    item.count++;
                }
            })
        }else{
            payload.count=1;
            state.shopList.unshift(payload);
        }
        
        return {...state}

    // case SETLIST:
    //     state.list = payload;
    //     return {...state}
        
    default:
        return {...state}
    }
}

export default legacy_createStore(routes,applyMiddleware(logger,thunk))
